<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>LayUI表格表单操作示例</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
</head>
<body>
    
    <!-- 表格页面 -->
    <div class="layui-fluid" style="padding: 15px;">
        <div class="layui-card">
            <div class="layui-card-header">
                <span>用户管理</span>
                <div class="layui-btn-group" style="float: right;">
                    <button class="layui-btn layui-btn-sm" id="addBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 添加
                    </button>
                </div>
            </div>
            <div class="layui-card-body">
                <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
            </div>
        </div>
    </div>

    <!-- 表格操作栏模板 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <!-- 表单弹出层内容 -->
    <div id="userForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="userFormFilter">
            <input type="hidden" name="id" id="userId">
            
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" placeholder="请输入姓名" class="layui-input" lay-verify="required">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input type="number" name="age" placeholder="请输入年龄" class="layui-input" lay-verify="required|number">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" name="email" placeholder="请输入邮箱" class="layui-input" lay-verify="required|email">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="gender" value="男" title="男" checked>
                    <input type="radio" name="gender" value="女" title="女">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status" lay-verify="required">
                        <option value="">请选择状态</option>
                        <option value="启用">启用</option>
                        <option value="禁用">禁用</option>
                    </select>
                </div>
            </div>
            
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="submitBtn">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <script src="https://www.layuicdn.com/layui/layui.js"></script>
    <script>
    layui.use(['table', 'layer', 'form'], function(){
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            $ = layui.$;

        // 模拟数据
        var userData = [
            {id: 1, name: '张三', age: 25, email: 'zhangsan@example.com', gender: '男', status: '启用'},
            {id: 2, name: '李四', age: 30, email: 'lisi@example.com', gender: '女', status: '启用'},
            {id: 3, name: '王五', age: 28, email: 'wangwu@example.com', gender: '男', status: '禁用'}
        ];
        
        // 用于标识当前操作类型
        var currentAction = '';

        // 渲染表格
        var tableIns = table.render({
            elem: '#userTable',
            data: userData,
            cols: [[ 
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'name', title: '姓名', width: 120},
                {field: 'age', title: '年龄', width: 80},
                {field: 'email', title: '邮箱', width: 200},
                {field: 'gender', title: '性别', width: 80},
                {field: 'status', title: '状态', width: 100},
                {title: '操作', toolbar: '#barDemo', width: 150, align: 'center'}
            ]],
            page: false,
            height: 'full-220'
        });

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            currentAction = 'add';
            openForm('添加用户', {});
        });

        // 表格工具栏事件
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这条记录吗?', function(index){
                    // 删除数据
                    for(var i = 0; i < userData.length; i++){
                        if(userData[i].id === data.id){
                            userData.splice(i, 1);
                            break;
                        }
                    }
                    // 重新渲染表格
                    tableIns.reload({
                        data: userData
                    });
                    layer.close(index);
                    layer.msg('删除成功', {icon: 1});
                });
            } else if(obj.event === 'edit'){
                currentAction = 'edit';
                openForm('修改用户', data);
            }
        });

        // 打开表单弹出层
        function openForm(title, data){
            layer.open({
                type: 1,
                title: title,
                content: $('#userForm'),
                area: ['500px', '600px'],
                success: function(){
                    // 先重置表单
                    $('#userForm form')[0].reset();
                    
                    if(currentAction === 'edit' && data.id){
                        // 如果是编辑，填充数据
                        form.val('userFormFilter', data);
                    } else {
                        // 如果是添加，确保id字段为空
                        $('#userId').val('');
                        // 设置默认值
                        form.val('userFormFilter', {
                            gender: '男',
                            status: ''
                        });
                    }
                    
                    // 重新渲染表单
                    form.render();
                }
            });
        }

        // 表单提交事件
        form.on('submit(submitBtn)', function(data){
            var formData = data.field;
            
            // 转换数据类型
            if(formData.age) {
                formData.age = parseInt(formData.age);
            }
            
            if(currentAction === 'edit' && formData.id){
                // 修改数据
                formData.id = parseInt(formData.id);
                for(var i = 0; i < userData.length; i++){
                    if(userData[i].id === formData.id){
                        userData[i] = formData;
                        break;
                    }
                }
                layer.msg('修改成功', {icon: 1});
            } else {
                // 添加数据 - 生成新ID
                var maxId = 0;
                if(userData.length > 0){
                    maxId = Math.max.apply(Math, userData.map(function(item){
                        return item.id;
                    }));
                }
                formData.id = maxId + 1;
                
                // 添加到数据数组
                userData.push(formData);
                layer.msg('添加成功', {icon: 1});
            }
            
            // 重新渲染表格
            tableIns.reload({
                data: userData
            });
            
            // 关闭弹层
            layer.closeAll();
            
            return false; // 阻止表单跳转
        });
    });
    </script>
</body>
</html>